package org.mil.logic;


import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mil.bean.dom.FileDO;
import org.mil.bean.dom.TrackDO;
import org.mil.bean.dom.TrackDOFactory;

import org.mil.util.TextUtil;

/**
 * 负责通过xml输入流解析媒体信息的阅读器
 * @author HZK
 *
 */
public class MediaInfoReader {

	private static MediaInfoReader singleton;

	public static MediaInfoReader getInstance() {
		if (singleton == null)
			singleton = new MediaInfoReader();
		return singleton;
	}

	/**
	 *  用dom4j中的SAXReader对xml格式的输入流进行解析
	 * @param InputStream
	 * @return 作为解析结果的Document对象
	 */
	private Document readDocument(InputStream xmlStream) {
		SAXReader reader = new SAXReader();
		reader.setEncoding("utf8");
		Document document = null;
		String encoding=PropertyReader.getMediaInfoCLIOutputEncoding();
		try {
			InputStreamReader isr=new InputStreamReader(xmlStream,encoding); 
			//InputSource isrc=new InputSource(isr);
			document = reader.read(isr);
		} catch (DocumentException e) {
			System.out.println("读取发生异常！\n");
			 e.printStackTrace();
		} catch (UnsupportedEncodingException e) {		
			e.printStackTrace();
		}
		return document;
	}

	/**
	 * 将xml形式的数据解析为一个面向对象的bean，也就是FileDO
	 * @param xmlStream
	 * @return
	 */
	public FileDO parseXML(InputStream xmlStream) {
		Document document = readDocument(xmlStream);
		if (document == null)
			return null;
		Element rootElement = document.getRootElement();
		if (rootElement == null || rootElement.elements() == null
				|| rootElement.elements().size() == 0)
			return null;
		Element fileElement = (Element) rootElement.elements().get(0);
		if (fileElement == null || fileElement.elements() == null)
			return null;
		if (!"file".equalsIgnoreCase(fileElement.getName()))
			return null;
		FileDO file = new FileDO();
		Element trackElement;
		for (Object obj : fileElement.elements()) {
			trackElement = (Element) obj;
			String type = trackElement.attributeValue("type");
			
			TrackDO track = TrackDOFactory.newInstance(type);
			//一些未知类型的track直接跳过，比如type=menu之类的
			if (track==null) continue;
			Element v;
			for (String k : track.getFieldNames()) {
				v = trackElement.element(TextUtil.Capitalize1stLetter(k));
				if (v != null)
					track.set(k, v.getText());
			}
			file.addTrack(track);
		}
		return file;

	}


}
